"""
Moodle backend

This file is part of polyglot, etc.
"""

import datetime
import re
import requests
from lxml.html import parse
from io import StringIO
from .support import Backend, Course, ResourceCategory, ResourcePlain, ResourceLink, ResourceRawHTML, Quiz, MultipartQuestion, MultipleChoiceQuestion, FreeResponseQuestion 

class MoodleQuiz(Quiz):
    def __init__(self, course, id, name):
        raw_id = id[len("module-"):]

        super().__init__(raw_id, name)
        print("ID: " + self.id)
        print("Name: " + name)
        self.course = course

    def questions(self):
        url = self.course.backend.base + "/mod/quiz/view.php?id=" + self.id
        splash_text = self.course.backend.session.get(url).text
        splash = parse(StringIO(splash_text)).getroot()

        form = splash.cssselect("form")[0]
        quiz_text = self.course.backend.session.post(form.attrib["action"], data = dict(form.fields)).text

        with open("quiz.html", "w") as f:
            f.write(quiz_text)

        quiz = parse(StringIO(quiz_text)).getroot()
        questions = quiz.cssselect(".que")

        for q in questions:
            text = etree.tostring(q.cssselect(".qtext")[0])

            for a in q.cssselect(".answer")[0]:
                print(etree.tostring(a.cssselect("label")[0]))

            print(text)



        question1 = MultipleChoiceQuestion("Is mathematics fun?", ["Absolutely!", "Definitely!"])
        question2A = FreeResponseQuestion("What's your favourite part?")
        question2B = FreeResponseQuestion("Why?")
        question2 = MultipartQuestion([question2A, question2B])

        return [question1, question2]

    def submit(self, responses):
        return True

class MoodleCourse(Course):
    def __init__(self, backend, htmlref):
        self.backend = backend

        self.grade_url = htmlref.cssselect("a")[0].attrib["href"]
        self.id = re.search("id=([^&]*)", self.grade_url).group(1)
        self.url = self.backend.base + "/course/view.php?id=" + str(self.id)

        (self.title, self.grade_summary) = [c.text_content().strip() for c in htmlref.cssselect("td")]
        self.grade_summary = float(self.grade_summary) / 100.0

        self.teacher = "N/A"

    def make_child(self, child):
        # Names are encoded a bit differently between quizzes/links versus labels

        instance_name = child.cssselect(".instancename")
        name = instance_name[0].text if len(instance_name) else child.text_content()

        t = child.attrib["class"].split(" ")

        if "url" in t:
            return ResourceLink(name, child.cssselect("a")[0].attrib["href"] + "&redirect=1")
        elif "quiz" in t:
            return MoodleQuiz(self, child.attrib["id"], name)
        elif "label" in t:
            return ResourcePlain(name, "") # TODO
        else:
            print("Unknwon resource type")
            print(t)
            return ResourcePlain(name, "Error, check logs")

    def make_section(self, section):
        name = section.attrib["aria-label"].strip()
        contents = section.cssselect("ul.section li")
        return ResourceCategory(name, [self.make_child(c) for c in contents])

    @property
    def resources(self):
        html = self.backend.session.get(self.url).text
        tree = parse(StringIO(html)).getroot()
        
        return [self.make_section(s) for s in tree.cssselect("li.section")]

class MoodleBackend(Backend):
    Config = ["Username", "Password", "School"]

    def login(self, config):
        self.base = "https://" + config["School"]

        auth = self.session.post("https://" + config["School"] + "/login/index.php", data = {
            "username": config["Username"],
            "password": config["Password"]
        })
        
        return True

    def fast_login(self, config):
        self.base = "https://" + config["School"]

    @property
    def courses(self):
        self.gradeset = self.session.get(self.base + "/grade/report/overview/index.php")
        tree = parse(StringIO(self.gradeset.text)).getroot()
        rows = tree.cssselect("#overview-grade tbody")[0].cssselect("tr:not(.emptyrow)")
        return [MoodleCourse(self, c) for c in rows]
